package com.zmn.oms.dubbo.impl.zmn.serviceprovider.order;

import com.alibaba.fastjson.JSON;
import com.zmn.base.engineer.common.dro.foreign.engineer.ForeignEngineerDetailInfoDRO;
import com.zmn.common.utils.date.DateUtil;
import org.apache.dubbo.config.annotation.Service;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.validator.ValidateResult;
import com.zmn.common.utils.validator.ValidatorUtil;
import com.zmn.oms.common.constant.OrderDistributeConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.dubbo.dto.zmn.order.serviceprovider.OrderDistributeBackDIO;
import com.zmn.oms.dubbo.dto.zmn.order.serviceprovider.OrderDistributeDIO;
import com.zmn.oms.dubbo.dto.zmn.order.serviceprovider.OrderDistributeDRO;
import com.zmn.oms.dubbo.dto.zmn.order.serviceprovider.OrderDistributeQueryDIO;
import com.zmn.oms.dubbo.impl.zmn.order.OrderWorkBaseRemoteService;
import com.zmn.oms.dubbo.interfaces.zmn.serviceprovider.order.ServProviderOrderDistributeRemoteService;
import com.zmn.oms.dubbo.utils.DubboConsts;
import com.zmn.oms.model.dto.work.modify.OrderDistributeDTO;
import com.zmn.oms.model.dto.work.modify.must.OrderAssignBackDTO;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.vo.work.DistributeVO;
import com.zmn.oms.model.vo.work.ZsOrderDistributeVO;
import com.zmn.oms.third.taobao.dto.api.TmallApiInvokResult;
import com.zmn.oms.third.taobao.service.TmallService;
import com.zmn.oms.zmn.business.interfaces.work.OrderWorkAssignBackBService;
import com.zmn.oms.zmn.business.interfaces.work.customwork.ZsCustomWorkBService;
import com.zmn.oms.zmn.business.interfaces.work.customwork.ZsDistributeWorkBService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 类描述： 服务商工单操作相关
 *
 * @author yule
 * @date 2020/7/6 16:16
 */
@Service(loadbalance = "roundrobin", timeout = 20000, retries = 2, version = DubboConsts.INTERFACE_VERSION, validation = "false")
public class ServProviderOrderDistributeRemoteServiceImpl extends OrderWorkBaseRemoteService implements ServProviderOrderDistributeRemoteService {
    private static final String TAG = "服务商-派单";
    @Autowired
    private OrderWorkAssignBackBService orderWorkAssignBackBService;
    @Autowired
    private ZsCustomWorkBService zsCustomWorkBService;
    @Autowired
    private TmallService tmallService;
    @Autowired
    private ZsDistributeWorkBService zsDistributeWorkBService;

    @Override
    public ResponseDTO<List<OrderDistributeDRO>> distributeMasterList(OrderDistributeQueryDIO distributeQueryDIO) {

        // 服务商门户派单师傅

        try {
            Long orderId = distributeQueryDIO.getOrderId();
            Long workId = distributeQueryDIO.getWorkId();

            OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
            OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderId);

            // 创建派单视图对象
            DistributeVO distributeVO = zsDistributeWorkBService.buildDistributeVO(orderWork, orderDetail, null);
            distributeVO.setDistributeEntry(OrderDistributeConsts.DISTRIBUTE_ENTRY_SP);

            // 服务商门户只有简单派单列表
            distributeVO.setOnlyBaseMasterList(true);
            distributeVO.setSimpleStatus(true);
            distributeVO.setRecommendStatus(false);
            distributeVO.setFairStatus(false);

            // 查询派单工程师
            zsDistributeWorkBService.getOrderDistributeMasterList(orderWork, orderDetail, distributeVO, null);
            List<ZsOrderDistributeVO> masterList;

            // 天猫差异化派单特殊处理，合并正常列表和消耗列表
            if (distributeVO.getDistributeBizType() == OrderDistributeConsts.DISTRIBUTE_BIZ_TYPE_SPECIAL
                    && distributeVO.getSpecialDistributeType() == OrderDistributeConsts.SPECIAL_DISTRIBUTE_TYPE_TMALL) {

                // 合并用的map
                Map<Integer, ZsOrderDistributeVO> mapData = Maps.newHashMap();

                // 消耗列表
                if (CollectionUtils.isNotEmpty(distributeVO.getMasterList())) {
                    for (ZsOrderDistributeVO vo : distributeVO.getMasterList()) {
                        mapData.put(vo.getMasterId(), vo);
                    }
                }

                // 正常列表
                if (CollectionUtils.isNotEmpty(distributeVO.getRecommendMasterList())) {
                    for (ZsOrderDistributeVO vo : distributeVO.getRecommendMasterList()) {
                        mapData.put(vo.getMasterId(), vo);
                    }
                }

                masterList = mapData.values().stream().collect(Collectors.toList());
            }
            else {
                masterList = distributeVO.getMasterList();
            }

            List<OrderDistributeDRO> distributeList;
            if (CollectionUtils.isNotEmpty(masterList)) {
                distributeList = BeanMapper.mapList(masterList, OrderDistributeDRO.class);
            }
            else {
                distributeList = Lists.newArrayList();
            }

            return ResponseDTO.success(distributeList);
        } catch (Exception e) {
            return ResponseDTO.fail(e.getMessage());
        }
    }

    @Override
    public ResponseDTO saveDistribute(OrderDistributeDIO distributeDIO) {
        //logger.info("[{}] 保存派单：{}", TAG, distributeDIO);

        ValidateResult validateResult = ValidatorUtil.validator(distributeDIO);

        if (!validateResult.isSuccess()) {
            logger.error("[{}] 参数错误：{}", TAG, validateResult.toString());
            return ResponseDTO.fail("提交参数错误：" + validateResult.toString());
        }

        try {
            OrderWork orderWork = orderWorkService.findOrderWorkByKey(distributeDIO.getOrderId(), distributeDIO.getWorkId());
            // 查询工程师信息
            // todo fubiao
            logger.info("saveDistribute#getEngineerDetailById 入参 [{}]",distributeDIO.getMasterId());
            ResponseDTO<ForeignEngineerDetailInfoDRO> cacheEngineerByEngineerId = engineerListRemoteService.getEngineerDetailById(distributeDIO.getMasterId());
            logger.info("saveDistribute#getEngineerDetailById 出参 [{}]", JSON.toJSONString(cacheEngineerByEngineerId));
            ForeignEngineerDetailInfoDRO baseEngineerDRO = cacheEngineerByEngineerId.getData();
            if (!cacheEngineerByEngineerId.isSuccess() || baseEngineerDRO == null) {
                return ResponseDTO.fail("工程师不存在");
            }

            // 天猫勤鸽店且未核销同步派单
            boolean isTmallDistribute = zsDistributeWorkBService.isTmallDistribute(orderWork);
            if (isTmallDistribute) {
                TmallApiInvokResult result = tmallService.syncOrderDistribute(orderWork.getOrderId(), baseEngineerDRO.getMobile(),
                        baseEngineerDRO.getRealName(), null);

                if (!result.isSuccess()) {
                    return ResponseDTO.fail(String.format("[派单失败]-%s", result.getMsg()));
                }
            }

            OrderDistributeDTO distributeDTO = BeanMapper.map(distributeDIO, OrderDistributeDTO.class);

            distributeDTO.setMasterName(baseEngineerDRO.getRealName());
            distributeDTO.setMasterPhone(baseEngineerDRO.getMobile());

            // 设置成已派单
            distributeDTO.setStatus(OrderStatusConsts.WORK_STATUS_DISTRIBUTE);
            // 派单路径
            distributeDTO.setDistributeWay(OrderDistributeConsts.DISTRIBUTE_WAY_SP);
            // 派单规则
            distributeDTO.setDistributeRule(OrderDistributeConsts.DISTRIBUTE_RULE_SIMPLE);
            // 派单入口
            distributeDTO.setDistributeEntry(OrderDistributeConsts.DISTRIBUTE_ENTRY_SP);
            distributeDTO.setOperateTime(DateUtil.getNow());
            zsCustomWorkBService.saveDistribute(distributeDTO);

            return ResponseDTO.success();
        } catch (OmsBaseException e) {
            //e.printStackTrace();
            return ResponseDTO.fail(e.getMessage());
        }
    }

    @Override
    public ResponseDTO saveAssignBack(OrderDistributeBackDIO orderDistributeBackDIO) {
        OrderAssignBackDTO orderAssignBackDTO = BeanMapper.map(orderDistributeBackDIO, OrderAssignBackDTO.class);

        try {
            orderAssignBackDTO.setStatus(OrderStatusConsts.WORK_STATUS_CONFIRM);
            orderAssignBackDTO.setResultStatus(OrderStatusConsts.WORK_RESULT_DOING);
            logger.info("保存分单撤回：{}", orderAssignBackDTO);
            orderWorkAssignBackBService.saveAssignBack(orderAssignBackDTO);
        } catch (OmsBaseException e) {
            return ResponseDTO.fail(e.getMessage());
        }

        return ResponseDTO.success();
    }
}
